/**
 * Created by wangfan on 2017/4/21.
 */


var editor; // use a global for the submit and return data rendering
$(document).ready(function () {

    var id =getUrlParam("id");
    var isdelete =getUrlParam("delete");
    var backid =getUrlParam("backid");
    var leadId =getUrlParam("leadId");
    var changeId=getUrlParam("changeId");
    if(changeId){
        $("#changeId").val(changeId);
    }

    if(leadId==6){
        $("#guanpianAudit").show();
        $("#kezhangAudit").hide();
        $("#zhuguanAudit").hide();
        $("#zhurenAudit").hide();

    }else if(leadId==7){
        $("#guanpianAudit").hide();
        $("#kezhangAudit").show();
        $("#zhuguanAudit").hide();
        $("#zhurenAudit").hide();

    }else if(leadId==8){
        $("#guanpianAudit").hide();
        $("#kezhangAudit").hide();
        $("#zhuguanAudit").show();
        $("#zhurenAudit").hide();

    }else if(leadId==9){
        $("#guanpianAudit").hide();
        $("#kezhangAudit").hide();
        $("#zhuguanAudit").hide();
        $("#zhurenAudit").show();

    }


    $(":radio[name='currentState']").click(function(){
        if($(":radio[name='currentState']:checked").val()==3){
            $("#suggestDiv").show();
            $("#suggestLabel").text("建议内容：");
        }else if($(":radio[name='currentState']:checked").val()==2){
            $("#suggestDiv").show();
            $("#suggestLabel").text("不同意原因：");

        }else{
            $("#suggestDiv").hide();
        };
    });
    $("#saveAudit").on("click", function () {

        $.ajax({
            type: "POST",
            url:"/commis/api/officeSupplies/officeSuppliesAudit",
            data:decodeURIComponent($('#auditForm').serialize(),true),
            async: false,
            error: function(request) {
                alert("审批失败，请检查填写内容是否正确，或确定是否已经审批过");
            },
            success: function(response) {
                //接收后台返回的结果
                if (response.status==0) {
                    confirm("审批成功！")
                    $.ajax({
                        url: '/commis/api/index/notify',
                        type: "GET",
                        async: false,
                        dataType: 'json',
                        success: function (result) {
                            if (result.status == 0) {

                                countNotify(result);
                            }

                        }, error: function (msg) {
                            alert("发生错误");
                        }
                    })
                    window.location.href="officeSuppliesDetail.html?id=" + id;
                } else if (response.status==1) {
                    alert("请检查是否填写正确!");
                }else if (response.status==2) {
                    alert("已经审批过了，请不要重复审批！");
                }

            }
        });


    });
    if(isdelete==1){

        $.ajax({
            url: '/commis/api/backNotify/remove?id='+backid,
            async: false,
            dataType: 'json',
            success: function (response) {
                if(response.status==0){
                    console.log("delete success");
                    $.ajax({
                        url: '/commis/api/index/notify',
                        type: "GET",
                        async: false,
                        dataType: 'json',
                        success: function (result) {
                            if (result.status == 0) {
                                countNotify(result);
                            }else{
                                alert(result.msg);
                            }


                        }, error: function (msg) {
                            alert("发生错误");
                        }
                    })
                }else {
                    console.log("delete failed");
                }


            }, error: function () {
                console.log("error");
            }
        });


    }
    $.ajax({
        url: '/commis/api/user/currentUser',
        type: "GET",
        async: false,
        dataType: 'json',
        data: {},
        success: function (response) {
            if (response.status == 0) {
                console.log("用户存在");
                user = response.data;
                userTypeId = user.userTypeId;
                var  communityId=user.community.communityId;
                if (userTypeId == 4) {
                    var communityName = user.community.communityName;

                    $("#communityName").val(communityName);

                }
                $.ajax({
                    url: '/commis/api/officeSupplies/'+id,
                    async: false,
                    dataType: 'json',
                    success: function (response) {
                        if (userTypeId != 4) {
                            $("#audit").show();
                        }else{
                            $(".authSpan").hide();
                        }
                        if(response.isOff==7||response.isOff==1||response.isOff==2){
                            $("#audit").show();
                            $(".authSpan").show();
                        }
                        $("#sctime").text(formatStringyyyyMMddTochinese(response.registerTime));

                        if(response.field2){
                            $("#attach").append('<a href="api/download/file?id=' + response.suppliesId + '&type=supplies&filename=' + response.field2 + '" class="btn btn-primary btn-xs" >下载</a>')
                        }
                        if(response.lastChange.isValid==0&&response.lastChange.currentAuditorId==user.userId&&userTypeId!=4){

                            $("#changeId").val(response.lastChange.changeId);
                            $("#alterFlag").val(1);
                            if(userTypeId==6){
                                $("#guanpianAudit").show();
                                $("#kezhangAudit").hide();
                                $("#zhuguanAudit").hide();
                                $("#zhurenAudit").hide();

                            }else if(userTypeId==7){
                                $("#guanpianAudit").hide();
                                $("#kezhangAudit").show();
                                $("#zhuguanAudit").hide();
                                $("#zhurenAudit").hide();

                            }else if(userTypeId==8){
                                $("#guanpianAudit").hide();
                                $("#kezhangAudit").hide();
                                $("#zhuguanAudit").show();
                                $("#zhurenAudit").hide();

                            }else if(userTypeId==9){
                                $("#guanpianAudit").hide();
                                $("#kezhangAudit").hide();
                                $("#zhuguanAudit").hide();
                                $("#zhurenAudit").show();

                            }

                        }

                        $.ajax({
                            url: '/commis/api/image/getImagePathForCom',
                            type: "POST",
                            async: false,
                            dataType: 'json',
                            data: {communityId:response.communityId},
                            success: function (response) {
                                if (response.status == 0) {
                                    $("#yinzhang").attr('src',"comImg/"+response.data.yinzhangImg);
                                    $("#jwhzrImg").attr('src',"signImg/"+response.data.signImg);
                                    // alert(response.data.yinzhangImg);

                                } else if (response.status == 1) {
                                    alert("获取图片出错");

                                }
                            }, error: function (msg) {
                                alert("获取图片出错");
                            }
                        })
                        // $("#subNO").text(response.submitNumber);
                        $("input[name='submitNumber']").val(response.submitNumber)
                        $("input[name='communityName']").val(response.community.communityName)
                        $("input[name='registerTime']").val(response.registerTime)
                        $("input[name='workexpType']").val(response.workexpType)
                        $("input[name='paymentMode']").val(response.paymentMode)
                        $("input[name='sum']").val(response.sum)
                        $("input[name='comment']").val(response.comment)
                        // $("#detail").append(' <tr><td class="col-md-1">社区名称</td> <td colspan="4"><span>'+response.community.communityName+'</span></td></tr>');
                        // $("#detail").append(' <tr><td class="col-md-1">申请时间</td> <td colspan="4"><span>'+response.registerTime+'</span></td></tr>');
                        // $("#detail").append(' <tr><td class="col-md-1">购置类型</td> <td colspan="4"><span>'+response.workexpType+'</span></td></tr>');
                        var length =response.details.length;
                        console.log(length);
                        // var detail =response.hasDetail;
                        if(length>0){
                            for(var i=0;i<length;i++){
                                var item = response.details[i];
                                $("input[name='no']:eq("+i+")").val(item.no)
                                $("input[name='suppliesName']:eq("+i+")").val(item.suppliesName)
                                $("input[name='unitCost']:eq("+i+")").val(item.unitCost)
                                $("input[name='count']:eq("+i+")").val(item.count)
                                $("input[name='cost']:eq("+i+")").val(item.cost)

                            }

                        }



                    }, error: function () {

                    }
                });

                $.ajax({
                    url: '/commis/api/image/getImagePathForOS',
                    type: "POST",
                    async: false,
                    dataType: 'json',
                    data: {osId:id},
                    success: function (response) {
                        if (response.status == 0) {
                            var  data =response.data;
                            for(var i=0;i<data.length;i++){
                                var item =data[i];
                                if(item.user_type_id==6){
                                    $("#guanpianSug").html(item.suggest?item.suggest:"&nbsp;&nbsp;   ");
                                    $("#guanpianDate").html(formatStringyyyyMMddTochinese(item.current_datetime));
                                    $("#guanpianImg").attr('src',"signImg/"+item.image);
                                    // $("#guanpianAudit").hide();


                                }else if(item.user_type_id==7){
                                    $("#kezhangSug").html(item.suggest?item.suggest:"&nbsp;&nbsp;  ");
                                    $("#kezhangDate").html(formatStringyyyyMMddTochinese(item.current_datetime));
                                    $("#kezhangImg").attr('src',"signImg/"+item.image);
                                    // $("#kezhangAudit").hide();


                                }else if(item.user_type_id==8){

                                    $("#zhuguanSug").html(item.suggest?item.suggest:" &nbsp;&nbsp; ");
                                    $("#zhuguanDate").html(formatStringyyyyMMddTochinese(item.current_datetime));
                                    $("#zhuguanImg").attr('src',"signImg/"+item.image);
                                    // $("#zhuguanAudit").hide();

                                }else if(item.user_type_id==9){
                                    $("#zhurenSug").html(item.suggest?item.suggest:" &nbsp;&nbsp; ");
                                    $("#zhurenDate").html(formatStringyyyyMMddTochinese(item.current_datetime));
                                    $("#zhurenImg").attr('src',"signImg/"+item.image);
                                    // $("#zhurenAudit").hide();



                                }

                            }
                            // $("#yinzhang").attr('src',"comImg/"+response.data.yinzhangImg);
                            // $("#jwhzrImg").attr('src',"signImg/"+response.data.signImg);

                            // alert(response.data.yinzhangImg);

                        } else if (response.status == 1) {
                            alert("获取图片出错");

                        }
                    }, error: function (msg) {
                        alert("获取图片出错");
                    }
                })

            } else if (response.status == 1) {
                alert("登录用户已经过期，请重新登录");
                window.parent.location.href = "../../login.html";
            }
        }, error: function (msg) {
            alert("登录用户已经过期，请重新登录");
            window.parent.location.href = "../../login.html";
        }
    })



    $('#changeTable').DataTable({

        ajax: "/commis/api/officeSupplies/changeDatatables?id=" + id,

        autoWidth: true,
        responsive: true,
        serverSide: true,
        processing: true,
        lengthChange: false,//是否允许用户改变表格每页显示的记录数
        ordering: false,//是否允许用户排序
        paging: true,//是否分页
        pagingType: "full_numbers",//除首页、上一页、下一页、末页四个按钮还有页数按钮
        searching: false,//是否开始本地搜索
        stateSave: false,//刷新时是否保存状态
        autoWidth: true,//自动计算宽度
        language: {
            emptyTable: "没有数据",
            search: "搜索:",
            paginate: {
                first: "首页",
                previous: "上一页",
                next: "下一页",
                last: "尾页"

            },
            lengthMenu: "每页 _MENU_ 条记录",
            zeroRecords: "没有找到记录",
            info: "第 _PAGE_ 页 ( 总共 _PAGES_ 页 )，共 _TOTAL_ 项",
            infoEmpty: "无记录",
            infoFiltered: "(从 _MAX_ 条记录过滤)"
        },
        columns: [
            {
                data: 'current_state',
                render: function (data, type, row) {
                    if (0 == data) {
                        return "待审核";
                    } else if (1 == data) {
                        return "同意"
                    }
                    else if (2 == data) {
                        return "不同意";
                    }
                    else if(3 == data)
                    {
                        return "建议";
                    }else if(4 == data)
                    {
                        return "更新";
                    }else if(5 == data)
                    {
                        return "重新提交";
                    }
                }
            }, {
                data: 'real_name', defaultContent: ""
            }, {
                data: 'current_datetime', defaultContent: ""

            }, {
                data: 'suggest', defaultContent: ""

            },  {
                data: 'submit_number', defaultContent: ""
            }]


    });







})
//设置框架
$(function () {
    $("#page_style").frame({
        float: 'left',
        menu_nav: '.Quick_operation',
        color_btn: '.skin_select',
        Sellerber_menu: '.list_content',
        Sellerber_header: '.Sellerber_header',
    });
});
$("#iframe_box").niceScroll({
    cursorcolor: "#888888",
    cursoropacitymax: 1,
    touchbehavior: false,
    cursorwidth: "5px",
    cursorborder: "0",
    cursorborderradius: "5px"
});
/*********************/
require.config({
    paths: {
        echarts: './js/dist'
    }
});